package com.foreveross.proxyip.application.impl.operate;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.foreveross.proxyip.application.operate.ChannelEntityApplication;
import com.foreveross.proxyip.core.pools.ChannelPool;
import com.foreveross.proxyip.core.pools.PoolsManager;
import com.foreveross.proxyip.core.zk.ZkAppCenter;
import com.foreveross.proxyip.entity.ChannelEntity;

import com.foreveross.proxyip.infra.PageData;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;

import com.foreveross.proxyip.monitor.vo.ChannelEntityVO;

import com.foreveross.proxyip.util.SecretUtil;

@Service
public class ChannelEntityApplicationImpl implements ChannelEntityApplication {
	@Resource(name = "entityHibernateRepository")
	IBaseRepository baseRepository;
	
	@Autowired
	private PoolsManager poolsManager;
	
	@Override
	public PageData findAllChannel( ChannelEntityVO vo,int pageIndex,
			int pageLen) throws Exception{
		if(pageIndex<=0){
			pageIndex=PageData.DEFAULT_PAGEINDEX;
		}
		if(pageLen<=0){
			pageLen=PageData.DEFAULT_PAGELEN;
		}
		List<Object> values=new ArrayList();
		
		//PoolsManager poolsManager = InstanceFactory
		//		.getInstance(PoolsManager.class);
		//List<ChannelEntity> channels = poolsManager.getChannelEntitys();
		List<ChannelEntity> channels = baseRepository.findAll(ChannelEntity.class);
		for(ChannelEntity e:channels)
		{
			if(e.getFlgDeleted()==0)//逻辑删除标志，判断是否已经删除
			{
				ChannelEntityVO v=new ChannelEntityVO(
						e.getId(),
						e.getCode(),
						e.getCreateName(),
						e.getCreateTime(),
						e.getCreator(),
						e.getFlgDeleted(),
						e.getIsValid(),
						e.getName(),
						e.getState(),
						e.getValidDefaultUrl(),
				        e.getLastTime());
				v.setSpeedGrade(e.getSpeedGrade());
				v.setTimes(e.getTimes());
				values.add(v);
			}
		}
		PageData p=new PageData();
		p.setPageIndex(pageIndex);
		p.setPageLen(pageLen);
		p.setResult(values);
		p.setDataSize(values.size());
		int pageCount=(int)values.size()/pageLen+((int)values.size()%pageLen>0?1:0);
		p.setPageCount(pageCount);
		return p;
	}
	
	
	
	@Override
	public void stopChannel(ChannelEntityVO vo){
		ChannelEntity channel=baseRepository.get(ChannelEntity.class, vo.getId());
		channel.setState(0);
		baseRepository.transSave(channel);
		try {
			ZkAppCenter.getInstance().getZK().delete(ZkAppCenter.getInstance().tasksPath+"/"+vo.getCode()+"_CheckInTask", -1);
			ZkAppCenter.getInstance().getZK().delete(ZkAppCenter.getInstance().tasksPath+"/"+vo.getCode()+"_CheckOutTask", -1);
			ZkAppCenter.getInstance().doNormalTask("stopChannel!"+vo.getCode());//删除所有应用的渠道池任务
		} catch (Exception e) {
			e.printStackTrace();
		}
		vo.setState(0);	
	}
	
	@Override
	public void startChannel(ChannelEntityVO vo){
		ChannelEntity channel=baseRepository.get(ChannelEntity.class, vo.getId());
		channel.setState(1);
		baseRepository.transSave(channel);
		poolsManager.register(vo.getCode());
//		ChannelPool pool = poolsManager.getChannelPoolMap().get(vo.getCode());
//		pool.open();
//		vo.setState(1);	
	}
	
	@Override
	public  ChannelEntity updateChannel(ChannelEntityVO vo){
		ChannelEntity updateChannel=baseRepository.get(ChannelEntity.class, vo.getId());
		String keword=null;
		try {
			keword=SecretUtil.secretEncrypt(vo.getPassword());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		updateChannel.setId(vo.getId());
		updateChannel.setCode(vo.getCode());
		updateChannel.setIsValid(vo.getIsValid());
//		updateChannel.setAuth(keword);
		updateChannel.setValidDefaultUrl(vo.getValidDefaultUrl());
		updateChannel.setLastTime(new Date());
		updateChannel.setSpeedGrade(vo.getSpeedGrade());
		updateChannel.setTimes(vo.getTimes());
		baseRepository.transSave(updateChannel);
		ChannelPool channel = this.poolsManager.getChannelPoolMap().get(vo.getCode());
		channel.channel = updateChannel.cloneInstance();
		return updateChannel;
	}
	
	@Override
	public  ChannelEntity deleteChannel(ChannelEntityVO vo){
		ChannelPool pool = poolsManager.getChannelPoolMap().get(vo.getCode());
		ChannelEntity channelEntity=baseRepository.get(ChannelEntity.class, vo.getId());
		channelEntity.setFlgDeleted(1);
		baseRepository.update(channelEntity);
		pool.destroy();
		return channelEntity;
		
	}

	@Override
	public ChannelEntity addChannel( ChannelEntityVO vo){
		String keword=null;
		try {
			keword=SecretUtil.secretEncrypt("pass");//暂时写死
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			ChannelEntity addChannel=new ChannelEntity();
		    addChannel.setCode(vo.getCode());
		    addChannel.setName(vo.getName());
		    addChannel.setCreateName(vo.getCreateName());
		    addChannel.setCreateTime(new Date());
		    addChannel.setFlgDeleted(0);
		    addChannel.setIsValid(vo.getIsValid());
		    addChannel.setAuth(keword);
		    addChannel.setState(1);
		    addChannel.setValidDefaultUrl(vo.getValidDefaultUrl());
		    addChannel.setHandtailorClass("");
		    addChannel.setLastTime(new Date());
		    addChannel.setSpeedGrade(vo.getSpeedGrade());
		    addChannel.setTimes(vo.getTimes());
		    try{
			baseRepository.transSave(addChannel);
		    }catch(Exception e){
		    	e.printStackTrace();
		    }
			poolsManager.register(vo.getCode());
		return addChannel;
	}



	@Override
	public boolean checkChannel(ChannelEntityVO vo) {
		boolean ischannel=false;//数据库中是否存在
		List<ChannelEntity> channels = baseRepository.findAll(ChannelEntity.class);
		for(ChannelEntity e:channels){
			if(vo.getCode().equals(e.getCode()))
			{
				ischannel=true;
			}
		}
		return ischannel;
	}



	@Override
	public Integer validatePass(Integer id,String pwd2) throws Exception {
		ChannelEntity channelEntity=baseRepository.get(ChannelEntity.class, id);
		String keword=SecretUtil.secretEncrypt(pwd2);
		if(StringUtils.equals(channelEntity.getAuth(), keword)){
			return 1;
		}
		return 0;
	}

	

}
